<template>
    <headerTop></headerTop>
    <div class="tao-row bg-white px-4 py-3">
        <stepp :items="['选择商品','确认订单信息','支付订单','收取商品']" :select="2"></stepp>
        <div class="user mt-3">
            <div class="stepTitle">
                <h2>实名证件信息</h2>
            </div>
            <div class="stepBody">
                <p>购票人：<Button type="primary" @click="pageInfo.showTicketBuyer=true"><span>选择购票人</span></Button></p>
                <div v-if="pageInfo.showTicketBuyer" class="border p-4 mt-4" style="width:700px;">
                    <p class="text-end mb-3"><addTicketBuyer @then="searchTicketBuyer"></addTicketBuyer></p>
                    <Table v-if="ticketbuyers" border @on-selection-change="selectTicketBuyer" :columns="pageInfo.ticketbuyerTable" :data="ticketbuyers">
                        <template #cardType="{row}">
                            <span v-if="row.cardType==0">身份证</span>
                            <span v-if="row.cardType==1">军官证</span>
                        </template>
                    </Table>
                </div>
            </div>
        </div>
        <div class="pay">
            <div class="stepTitle">
                <h2>选择付款方式</h2>
            </div>
            <div class="stepBody">
                <p><Radio v-model="pageInfo.payMode" label="payinline" true-value>网上付款</Radio></p>
            </div>
        </div>
        <div class="orderList">
            <div class="stepTitle">
                <h2>商品清单</h2>
            </div>
            <div class="stepBody">
                <Table v-if="seatData" border :columns="pageInfo.detailedListTable" :data="seatData">
                    <template #itemName="{ row }">
                        {{items.itemName}}
                    </template>
                    <template #seatId="{ row }">
                        <span>{{ (row.x)+'排'+(row.y)+'座' }}</span>
                    </template>
                    <template #num="{ row }">
                        <span>1</span>
                    </template>
                </Table>
            </div>
        </div>
        <div class="invoice">
            <div class="stepTitle">
                <h2>我要开发票</h2>
            </div>
            <div class="stepBody">
                <div class="border p-3">
                    <Tabs value="name1" :animated="false">
                        <TabPane label="公司" name="name1">
                            <Form :model="pageInfo.invoice" :label-width="80" style="width: 300px">
                                <FormItem label="公司抬头:">
                                    <Input v-model="pageInfo.invoice.invoiceHead" placeholder="请输入公司抬头"/>
                                </FormItem>
                                <FormItem label="公司税号:">
                                    <Input v-model="pageInfo.invoice.invoiceId" placeholder="请输入公司税号"/>
                                </FormItem>
                                <FormItem>
                                    <Button type="primary" @click="invoiceConfirm(1)">确认发票信息</Button>
                                </FormItem>
                            </Form>
                        </TabPane>
                        <TabPane label="个人" name="name2">
                            <Form :model="pageInfo.invoice" :label-width="80" style="width: 300px">
                                <FormItem>
                                    <Button type="primary" @click="invoiceConfirm(0)">确认发票信息</Button>
                                </FormItem>
                            </Form>
                        </TabPane>
                    </Tabs>
                </div>
            </div>
        </div>
        <div class="discount">
            <div class="stepBody">
                <div class="div-row">
                    <p class="p-right">
                        <Space direction="vertical">
                            <Checkbox v-model="pageInfo.isNeedInsurance">
                                <span>购买“安心订票保险”，本单保费金额：20.00 元</span>
                            </Checkbox>
                        </Space>
                    </p>
                    <p class="p-right">查看 <a href="#">保险服务说明</a> 和 <a href="#">《安心订票保险条款》</a></p>
                    <p class="p-right">购买保险，请填写真实姓名</p>
                    <p class="p-right"><strong>商品金额： </strong><span class="span-red">¥{{goodsPrice}}</span></p>
                    <p class="p-right" v-if="pageInfo.isNeedInsurance"><strong>商品保险： </strong>+ <span class="span-red">¥20</span></p>
                </div>
                <div class="div-row">
                    <p class="p-right"><strong>待支付总额：</strong><span class="span-red">¥{{totalPrice}}</span></p>
                    <p class="p-right">
                        <Space direction="vertical">
                            <Checkbox v-model="pageInfo.readAndUnify">
                                <strong>我已阅读并同意</strong>
                                <Tooltip placement="top">
                                    《订购服务条款》
                                    <template #content>
                                        <div style="width: 200px;white-space: break-spaces;">
                                            <p>本服务条款适用于所有登陆逃票网/中国票务在线的用户，包括个人用户、团体用户、单位用户等。</p>
                                            <p>逃票网/中国票务在线，以下简称“本网站”。</p>
                                            <p>登陆逃票网/中国票务在线的用户，包括个人用户、团体用户、单位用户。以下统称“用户”。</p>
                                        </div>
                                    </template>
                                </Tooltip>
                                <Tooltip placement="top">
                                    《退换货约定》
                                    <template #content>
                                        <div style="width: 200px;white-space: break-spaces;">
                                            <p>（1） 符合退、换货时间规定（依据：主办方通知的因演出取消/延期安排的退票时间、转场时间段）；</p>
                                            <p>（2） 需将票品完好无损退回；</p>
                                            <p>（3） 如开发票，需将发票完好无损退回；</p>
                                        </div>
                                    </template>
                                </Tooltip> 
                                <Tooltip placement="top">
                                    《退款约定》
                                    <template #content>
                                        <div style="width: 200px;white-space: break-spaces;">
                                            <p>1、因不可抗力因素导致演出取消或延期，逃票网会主动与您确认变更或退款事宜，不收取任何手续费。</p>
                                            <p>2、办理退款或变更要求需符合时间规定（依据：主办方通知的因演出取消/延期安排的退款时间、转场时间段）。</p>
                                        </div>
                                    </template>
                                </Tooltip>
                            </Checkbox>
                        </Space>
                    </p>
                    <p class="p-right">同意“票品为不记名凭证，请您妥善保管，遗失不补”</p>
                    <p class="p-right pt-5">
                        <Button type="primary" @click="submitOrder" :disabled="!pageInfo.isSubmit||!pageInfo.readAndUnify">同意以上协议并提交订单</Button>
                    </p>
                </div>
            </div>
        </div>
    </div>
    <router-view></router-view>
    <footerr></footerr>
</template>
<script setup>
import stepp from "../../components/step/step.vue"
import {ref,reactive,computed} from "vue"
import {useRoute,useRouter} from "vue-router"
import {getItems,ticketbuyerlist,submitorder} from "../../utils/api"
import {usePayOrder} from "../../store/payOrderStore"
import {useLoginStore} from "../../store/useLoginStore"
import {storeToRefs} from "pinia"
import {Notice} from "view-ui-plus"

const route = useRoute();
const router = useRouter();

const payOrder = usePayOrder();
const loginUser = useLoginStore();

let {seatData,comData} = storeToRefs(payOrder);

if(JSON.stringify(payOrder)=='{}'||Object.keys(seatData.value).length==0||JSON.stringify(comData.value)=='{}'){
    setTimeout(() => {
        Notice.error({title:"你没有订单，即将跳转到首页",duration:1,onClose(){
            location.href="/";
        }});
    }, 500);
}


/**
 * 商品信息
 */
let items = ref({});

getItems(comData.value.itemId).then(({data})=>{
    items.value=data.data;
})

/**
 * 商品总价
 */
const goodsPrice = computed(()=>{
    let tp = 0;
    for(var e of seatData.value){
        tp+=e.price;
    }
    return tp;
})

/**
 * 支付总价
 */
const totalPrice = computed(()=>{
    let tp = 0;
    for(var e of seatData.value){
        tp+=e.price;
    }
    if(pageInfo.isNeedInsurance){
        tp+=20;
    }
    return tp;
})

/**
 * 页面信息
 */
let pageInfo = reactive({
    ticketbuyerTable:[
        {
            type: 'selection',
            width: 60,
            align: 'center'
        },
        {
            title:"姓名",
            key:"name"
        },
        {
            title:"卡类型",
            slot:"cardType"
        },
        {
            title:"身份证号",
            key:"idCard"
        }
    ],
    detailedListTable:[
        {
            title:"商品名称",
            slot:'itemName'
        },
        {
            title:"座位号",
            slot:'seatId'
        },
        {
            title:"价格",
            key:"price"
        },
        {
            title:"数量",
            slot:"num"
        },
        {
            title:"价格小计（元）",
            key:"price"
        },
    ],
    ticketbuyers:[],
    detailedList:[],
    payMode:'',
    invoice:{
        invoiceHead:null,
        invoiceId:null,
        invoiceType:0
    },
    showTicketBuyer:false,
    isNeedInsurance:false,
    readAndUnify:false,
    isSubmit:false
})

function ticketbuyerChange(){
    if(pageInfo.ticketbuyers.length==seatData.value.length){
        Notice.success({title:"人数等于购票数量,请不要继续选择了"});
        pageInfo.isSubmit=true;
    }else if(pageInfo.ticketbuyers.length>seatData.value.length){
        Notice.error({title:"人数已超过购票数量"});
        pageInfo.isSubmit=false;
    }else if(pageInfo.ticketbuyers.length<seatData.value.length){
        pageInfo.isSubmit=false;
    }
}
/**
 * 购票人信息
 */
let ticketbuyers = reactive([]);
function searchTicketBuyer(){
    ticketbuyerlist(1).then(({data})=>{
        ticketbuyers.length=0;
        ticketbuyers.push(...data.data);
    })
}
searchTicketBuyer();
function selectTicketBuyer(arr){
    pageInfo.ticketbuyers.length=0;
    pageInfo.ticketbuyers=arr;
    ticketbuyerChange();
}

let orderInfo = {
    userId:"",
    schedulerId:"",
    itemId:0,
    sourceType: 0, //是否需要
    isNeedInvoice: null,//是否需要发票
    invoiceType:null,//发票类型
    invoiceHead: null,//发票头
    isNeedInsurance: null,//是否需要保险
    seatPositions: "",//座位位置
    linkIds: ""
};

/**
 * 确认发票信息
 */
function invoiceConfirm(invoice){
    orderInfo.isNeedInvoice=1;
    orderInfo.invoiceType=invoice;
    orderInfo.invoiceHead=pageInfo.invoice.invoiceHead;
    Notice.success({title:`修改发票信息为:${orderInfo.invoiceType==0?'个人':'公司'}`});
}

function submitOrder(){
    orderInfo.schedulerId=comData.value.timePlan;
    orderInfo.itemId=comData.value.itemId;
    orderInfo.isNeedInsurance=pageInfo.isNeedInsurance?1:0;
    let seatPositions = "";
    for(var e of seatData.value){
        seatPositions+=(e.x)+"_"+(e.y)+",";
    }
    orderInfo.seatPositions=seatPositions.substring(0,seatPositions.length-1);
    let linkIds = "";
    for(var e of pageInfo.ticketbuyers){
        linkIds+=e.id+",";
    }

    orderInfo.linkIds=linkIds.substring(0,linkIds.length-1);
    orderInfo.userId = loginUser.loginUser.loginUser.id;
    submitorder(orderInfo).then(({data})=>{
        if(data.errorCode=="1006"){
            Notice.error({title:data.msg});
        }else if(data.errorCode="0000"){
            router.push({path:"/paymethod",query:{orderNo:data.data.orderNo}});
            payOrder.seatData=[];
            payOrder.comData=null;
        }
        
    })
}

</script>
<style lang="less">
    .stepTitle{
        position: relative;
        h2{
            font-size: 14px;
            height: 30px;
            line-height: 30px;
            color: #ff3c1b;
            padding-left: 10px;
            font-weight: 400;
        }   
    }
    .stepTitle::after{
        content: "";
        position: absolute;
        left: 0;
        top: 100%;
        z-index: 0;
        width: 120px;
        border-bottom: 1px solid #ff3c1b;
    }
    .stepBody{
        padding: 10px 0;
        border-top: 1px solid #d7d7d7;
        .div-row{
            padding: 20px;
            .p-right{
                line-height: 24px;
                text-align: end;
                .span-red{
                    color: #ff3c1b;
                }
            }
        }
        .div-row:not(:last-child){
            border-bottom: 1px dashed #c3c3c3;
        }
    }
</style>